<?php

namespace App\Http\Controllers\Inspection;

use Illuminate\Http\Request;
use App\Models\Inspection\Circle;
use App\Http\Controllers\Controller;

/**
 * 巡检圈逻辑控制器
 *
 * Date: 23/04/2018
 * @author George
 * @package App\Http\Controllers\Inspection
 */
class CircleController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $this->validate($request, ['line_id' => 'required']);
        $line_id = $request->get('line_id');
        $paginate = $request->get('paginate');
        $query = Circle::query();
        $query->where('line_id', $line_id);

        if ($paginate) {
            $collection = $query->paginate($paginate);
        } else {
            $collection = $query->get();
        }

        return success($collection);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $attributes = $this->validate($request, [
            'project_id' => 'required',
            'line_id' => 'required',
            'name' => 'required',
        ]);

        $attributes['company_id'] = Auth::user()->company_id;
        $circle = Circle::create($attributes);
        return stored($circle);
    }

	/**
	 * 获取详情
	 *
	 * Date: 25/04/2018
	 * @author George
	 * @param Circle $circle
	 * @return \Illuminate\Http\JsonResponse
	 */
    public function show(Circle $circle)
    {
    	$circle->nodes = $circle->nodes()->get();
        return success($circle);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Inspection\Circle  $circle
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Circle $circle)
    {
        $attributes = $this->validate($request, [
            'line_id' => 'nullable',
            'name' => 'nullable',
        ]);

        $circle->update($attributes);
        return updated($circle);
    }

    /**
     * Date: 23/04/2018
     * @author George
     * @param Circle $circle
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function destroy(Circle $circle)
    {
        $circle->delete();
        return deleted();
    }
}
